<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import {
  deleteMaterialRequisition,
  executeInbound,
  executeOutbound,
  getMaterialRequisitionList,
} from "@/api/ProductPicking/index";
import { MaterialRequisitionItem } from "@/api/ProductPicking/res";
import { ElMessage, ElMessageBox } from "element-plus";

// mockData
let procedureData = ref(["工序一", "工序二", "工序三"]);
let flowData = ref([
  "工艺流程一",
  "工艺流程二",
  "工艺流程三",
  "工艺流程四",
  "工艺流程五",
]);
let searchData = ref({
  requisitionCode: "",
  workOrderCode: "",
  requisitionDate: "",
  taskCode: "",
  procedureName: "",
});
let params = ref({
  currentPage: 1,
  pageSize: 10,
});
let ifSearch = ref(false);
let tableData = ref();
let total = ref(0);
let showDatePicker = ref(false);
let loading = ref(false);
const $router = useRouter();
const filteredSearchData = {};

const handler = (page) => {
  params.value.currentPage = page;
  if (ifSearch.value) {
    fetchMaterialList(filteredSearchData);
  } else {
    fetchMaterialList();
  }
};
const sizeHandler = (page_size) => {
  params.value.pageSize = page_size;
  if (ifSearch.value) {
    fetchMaterialList(filteredSearchData);
  } else {
    fetchMaterialList();
  }
};
const gotoAdd = () => {
  $router.push("/storage/entrance/material/addMaterial");
};
const gotoDetail = (row) => {
  $router.push({
    path: "/storage/entrance/material/materialDetail",
    query: { objectId: row.objectId },
  });
};
const gotoEdit = (row) => {
  $router.push({
    path: "/storage/entrance/material/editMaterial",
    query: { objectId: row.objectId },
  });
};

const handleOutbound = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将领料单 "${row.requisitionName}" 标记为已出库吗？`,
      "确认出库",
      {
        confirmButtonText: "确认出库",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await executeOutbound(row.objectId);

    ElMessage({
      message: "出库操作成功",
      type: "success",
    });

    fetchMaterialList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("出库操作失败:", error);
      ElMessage.error("出库操作失败");
    }
  }
};

const handleInbound = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要将领料单 "${row.requisitionName}" 撤回吗？`,
      "确认",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await executeInbound(row.objectId);

    ElMessage({
      message: "修改未出库操作成功",
      type: "success",
    });

    fetchMaterialList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("修改未出库操作失败:", error);
      ElMessage.error("修改未出库操作失败");
    }
  }
};

const fetchMaterialList = async (data?) => {
  try {
    loading.value = true;
    const TotalRes = await getMaterialRequisitionList();
    total.value = TotalRes.results.length;
    const response = await getMaterialRequisitionList(data, params.value);
    console.log(response);
    tableData.value = response.results;
    if (ifSearch.value) {
      total.value = response.results.length;
    }
  } catch (error) {
    console.error("获取领料单列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleDelete = async (row: MaterialRequisitionItem) => {
  try {
    await deleteMaterialRequisition(row.objectId);
    fetchMaterialList();
    ElMessage({ message: "删除成功", type: "success" });
  } catch (error) {
    console.error("删除领料单失败:", error);
  }
};

const reset = () => {
  searchData.value = {
    requisitionCode: "",
    workOrderCode: "",
    requisitionDate: "",
    taskCode: "",
    procedureName: "",
  };
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  ifSearch.value = false;
  fetchMaterialList();
};
const onSearch = () => {
  let allFieldsEmpty = true;
  Object.keys(filteredSearchData).forEach((key) => {
    delete filteredSearchData[key];
  });
  for (const key in searchData.value) {
    if (searchData.value[key] !== "") {
      allFieldsEmpty = false;
      filteredSearchData[key] = searchData.value[key];
    }
  }
  ifSearch.value = !allFieldsEmpty;
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  fetchMaterialList(filteredSearchData);
};

onMounted(() => {
  fetchMaterialList();
});
</script>

<template>
  <div style="padding: 20px">
    <el-card>
      <div class="operateContainer">
        <div
          class="formContainer"
          :style="showDatePicker ? 'height:85px' : 'height:32px'"
        >
          <el-form inline :model="searchData">
            <el-form-item prop="requisitionCode">
              <el-input
                placeholder="请输入领料单编号/名称"
                style="width: 250px"
                v-model="searchData.requisitionCode"
              ></el-input>
            </el-form-item>
            <el-form-item prop="workOrderCode">
              <el-input
                placeholder="请输入工单编号/名称"
                style="width: 250px"
                v-model="searchData.workOrderCode"
              ></el-input>
            </el-form-item>
            <el-form-item prop="requisitionDate">
              <el-date-picker
                style="width: 250px"
                type="date"
                placeholder="请选择领料日期"
                v-model="searchData.requisitionDate"
              ></el-date-picker>
            </el-form-item>
            <div style="margin-top: 20px">
              <el-form-item prop="taskCode">
                <el-input
                  placeholder="请输入任务编号/名称"
                  style="width: 250px"
                  v-model="searchData.taskCode"
                ></el-input>
              </el-form-item>
              <el-form-item prop="procedureName">
                <el-select
                  v-model="searchData.procedureName"
                  placeholder="请选择工序"
                  style="width: 250px"
                >
                  <el-option
                    v-for="item in procedureData"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select placeholder="请选择工艺流程" style="width: 250px">
                  <el-option
                    v-for="item in flowData"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="searchOperate">
          <div class="button">
            <el-button type="primary" plain style="width: 80px" @click="reset"
              >重置</el-button
            >
            <el-button type="primary" style="width: 80px" @click="onSearch"
              >查询</el-button
            >
          </div>
          <div class="more">
            <el-button
              type="primary"
              link
              @click="showDatePicker = !showDatePicker"
              >更多</el-button
            >
            <el-icon color="#1B9AEE" :class="{ 'rotate-180': showDatePicker }">
              <CaretBottom />
            </el-icon>
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>
        <span style="font-weight: bold">生产领料</span>
      </template>
      <div class="operate">
        <el-button style="width: 80px" type="primary" @click="gotoAdd"
          >新增</el-button
        >
        <el-button style="width: 80px" type="primary" plain>删除</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="margin-top: 15px"
        border
      >
        <el-table-column type="selection" align="center"> </el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
          fixed="left"
        ></el-table-column>
        <el-table-column
          align="center"
          label="领料单名称"
          width="100"
          fixed="left"
          prop="requisitionName"
        >
          <template #="{ row }">
            <el-button link type="primary" @click="gotoDetail(row)">{{
              row.requisitionName
            }}</el-button>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="领料单编号"
          width="100"
          fixed="left"
          prop="requisitionCode"
        ></el-table-column>
        <el-table-column
          align="center"
          label="领料日期"
          width="100"
          prop="requisitionDate"
        ></el-table-column>
        <el-table-column
          align="center"
          label="领料人"
          prop="receiver"
          width="120"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工单名称"
          width="90"
          prop="workOrderName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工单编号"
          width="110"
          prop="workOrderCode"
        ></el-table-column>
        <el-table-column
          align="center"
          label="任务名称"
          width="90"
          prop="taskName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="任务编号"
          width="90"
          prop="taskCode"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工艺路线"
          width="100"
          prop="processRoute"
        ></el-table-column>
        <el-table-column
          align="center"
          label="工序名称"
          width="90"
          prop="procedureName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="物料信息"
          width="110"
          prop="materialInfo"
        ></el-table-column>
        <el-table-column
          align="center"
          label="领料总数"
          width="90"
          prop="totalQuantity"
        ></el-table-column>
        <el-table-column
          align="center"
          label="备注"
          width="160"
          prop="remark"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleOutbound(row)"
              v-if="row.status === '未出库'"
            >
              出库
            </el-button>
            <el-button
              link
              type="primary"
              @click="gotoEdit(row)"
              v-if="row.status === '未出库'"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleDelete(row)"
              v-if="row.status === '未出库'"
              >删除</el-button
            >

            <el-button
              link
              type="primary"
              @click="handleInbound(row)"
              v-if="row.status === '已出库'"
              >撤回</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.currentPage"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="prev,pager,next,jumper,->,sizes,total"
        :total="total"
        @current-change="handler"
        @size-change="sizeHandler"
        style="margin-top: 10px"
      ></el-pagination>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.operateContainer {
  display: flex;
  align-content: center;
  justify-content: space-between;

  .formContainer {
    width: 1060px;
    height: 32px;
    transition: height 0.3s ease; // 添加高度变化的过渡效果
    overflow: hidden; // 防止内容溢出

    .el-form-item {
      margin-bottom: 0;
    }
  }

  .searchOperate {
    display: flex;
    align-items: center;

    .more {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

/* 定义旋转动画 */
.rotate-180 {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}
</style>
